package com.lituoxy.dialer.updata;

import android.app.ProgressDialog;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpHelper {
	
	private final static String TAG_DATA_SET = "dataset";
	private final static String TAG_USER_DATA_SET = "userdataset";
	private final static String TAG_TRAIN_POS = "trainpos";
	private final static String TAG_TRAIN_ORDER = "trainorder";
	private final static String TAG_TRAIN_SECTOR = "sector";

	private final static String URL_BASE = "http://app.lituoxy.com:8091/api";
	private final static String URL_BASE_TRAIN = URL_BASE + "/" + "";
	private final static String URL_DATA_SET = URL_BASE_TRAIN + "/" + TAG_DATA_SET;
	private final static String URL_USER_DATA_SET = URL_BASE_TRAIN + "/" + TAG_USER_DATA_SET;
	private final static String URL_TRAIN_POS = URL_BASE_TRAIN + "/" + TAG_TRAIN_POS;
	private final static String URL_TRAIN_ORDER = URL_BASE_TRAIN + "/" + TAG_TRAIN_ORDER;
	private final static String URL_TRAIN_SECTOR = URL_BASE_TRAIN + "/" + TAG_TRAIN_SECTOR;
	
	public static JSONObject getHttpDataSet() {
		
		//String url = "http://app.lituoxy.com:8091/api/tdprj_a543/dataset";
		String data = convertStreamToString(getHttpRawData(URL_DATA_SET));
		
		return convertStringToJason(data);
	}
	
	public static JSONArray getHttpSectorSet() {
		//String url = "http://app.lituoxy.com:8091/api/tdprj_a543/sector";
		String data = convertStreamToString(getHttpRawData(URL_TRAIN_SECTOR));
		return convertStringToJasonArray(data);
	}
	
	public static JSONObject getHttpUserDataSet() {
		
		//String url = "http://app.lituoxy.com:8091/api/tdprj_a543/userdataset";
		String data = convertStreamToString(getHttpRawData(URL_USER_DATA_SET));
		
		return convertStringToJason(data);
	}
	
	public static JSONArray getHttpTrainPos() {
		//String url = "http://app.lituoxy.com:8091/api/tdprj_a543/trainpos";
		String data = convertStreamToString(getHttpRawData(URL_TRAIN_POS));
		return convertStringToJasonArray(data);
	}
	
	public static JSONArray getHttpTrainAllOrders(String train) {
		
		//String url = "http://app.lituoxy.com:8091/api/tdprj_a543/trainpos";
		String data = convertStreamToString(getHttpRawData(URL_TRAIN_ORDER + "?devid=" + train));
		return convertStringToJasonArray(data);
	}

	public static void confirmHttpTrainOrder(String train, String _id, JSONObject updateOrder) {
		try {
			setHttpRawData(URL_TRAIN_ORDER + "/" + _id, 
					train, train, updateOrder.toString());
			Log.i("===Send===", URL_TRAIN_ORDER);
			Log.i("===Send===", _id);
			Log.i("===Send===", train);
			Log.i("===Send===", updateOrder.toString());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void confirmHttpTrainInfo(String train, String _id, String json) {
		try {
			setHttpRawData(URL_TRAIN_POS + "/" + _id, 
					train, train, json);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static InputStream getHttpRawData(String urlStr) {
		
		InputStream stream = null;
		
		HttpURLConnection connect;
		try {
			URL url = new URL(urlStr);

			connect = (HttpURLConnection)url.openConnection();
			connect.setConnectTimeout(2000);
			connect.setRequestMethod("GET");
			int reqCode = connect.getResponseCode();
			if (reqCode == 200) {
				return connect.getInputStream();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stream;
	}
	
	public static String convertStreamToString(InputStream stream) {
		if (stream == null) {
			return null;
		}
		
		String jasonData = "";
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		
		try {
			while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
				out.write(buffer, 0, len);
			}
			
			jasonData = new String(out.toByteArray());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return jasonData;
	}
	
	private static JSONArray convertStringToJasonArray(String data) {
		
		if (data == null || data.isEmpty()) {
			return null;
		}
		
		JSONArray jason = null;
		try {
			jason = new JSONArray(data);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jason;
	}
	
	public static JSONObject convertStringToJason(String data) {
		
		if (data == null || data.isEmpty()) {
			return null;
		}
		
		JSONObject jason = null;
		try {
			jason = new JSONObject(data);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jason;
	}
	
	private static void setHttpRawData(String urlStr, String username, String password, String data) throws ClientProtocolException, IOException {
		
		HttpPut put = new HttpPut(urlStr);
        byte[] encodedPassword = (username + ":" + password).getBytes();  
        put.addHeader("Authorization", "Basic " + Base64.encodeToString(encodedPassword, Base64.NO_WRAP));
        put.addHeader("Content-Type", "application/json");
        put.addHeader("charset", HTTP.UTF_8);
        put.setEntity(new StringEntity(data, "utf-8"));
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(put);
        Log.i("===Send===", "请求返回代码:" + response.getStatusLine().getStatusCode());
	}
	
	public static File getFileFromServer(String urlPath, String dirStr, String fileName, ProgressDialog pd) throws Exception {
		//如果相等的话表示当前的sdcard挂载在手机上并且是可用的
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			URL url = new URL(urlPath);
			HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			//获取到文件的大小 
			if(pd != null){
				pd.setMax(conn.getContentLength());
			}
			InputStream is = conn.getInputStream();
			File file = new File(dirStr, fileName);
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len ;
			int total=0;
			while((len =bis.read(buffer))!=-1){
				fos.write(buffer, 0, len);
				total+= len;
				//获取当前下载量
				if(pd != null){
					pd.setProgress(total);
				}
			}
			fos.close();
			bis.close();
			is.close();
			return file;
		}else{
			return null;
		}
	}
}
